#include "testApp.h"
#include <iostream>
#include <fstream>


#define DEFAULT_TEMP_COLLECTION -10000
#define X_ANCHOR 250

// energyhive user name and password are required for retrieval of data
// change the defines to yours

#define USERNAME "YOURlogin"
#define PASSWORD "YOURpassword"

// MAC address is for the sensor - this one is a public source
#define MAC "001F1F3A8B70"

// Labels for the headings
#define LABEL_1 "Average"
#define LABEL_2 "University"
#define LABEL_3 "Appliance"
#define LABEL_4 "Home"

//--------------------------------------------------------------
void testApp::setup(){
	std::stringstream loginURL;
	std::stringstream instantReadingURL;
	std::stringstream macURL;
	
	ofSetFrameRate(12);
	ofBackground(255, 255, 255);
	myFont.loadFont("Verdana.ttf", 17);
	
	temperatureCollectionSize = 20;
	groupCollectionSize = 3;
	
	temperatureCollectionGroup1 = new int[ temperatureCollectionSize ];
	temperatureCollectionGroup2 = new int[ temperatureCollectionSize ];
	temperatureCollectionGroup21 = new int[ temperatureCollectionSize ];
	temperatureCollectionGroup3 = new int[ temperatureCollectionSize ];
	
	for(int i=0; i<temperatureCollectionSize; i++)
	{
		temperatureCollectionGroup1[ i ] = DEFAULT_TEMP_COLLECTION;
		temperatureCollectionGroup2[ i ] = DEFAULT_TEMP_COLLECTION;
		temperatureCollectionGroup21[ i ] = DEFAULT_TEMP_COLLECTION;
		temperatureCollectionGroup3[ i ] = DEFAULT_TEMP_COLLECTION;
	}
	
	temperatureGroupUpdateIndex1 = temperatureGroupUpdateIndex2 = temperatureGroupUpdateIndex3 = 0;
	
	ofxHttpEvents.addListener(this);
	
	//http.addUrl("http://status2.energyhive.co.uk/fp_data.json");
	loginURL << "http://status2.energyhive.co.uk/get_hid.json?user=" << USERNAME << "&pass=" << PASSWORD;
	cout << loginURL.str() << endl;
	
	http.addUrl(loginURL.str());
	// If fail (401) then the log in was not successful - exit.
	
	instantReadingURL << "http://status2.energyhive.co.uk/hive_data.json?hid=" << hid << "&key=" << key << "&avg=0";
	cout << instantReadingURL.str() << endl;
	http.addUrl(instantReadingURL.str());
	
	macURL << "http://www.dehems.org/data/get_status.json?iHateIE=1285496040&mac=" << MAC;
	cout << macURL.str() << endl;
	http.addUrl(macURL.str());

	//ofSetBackgroundAuto(false);
	
	ofSetCircleResolution( 100 );
}

void testApp::newResponse(ofxHttpResponse & response){
	parseJSON(response.responseBody);
}

void testApp::newError(string error){
    printf("new error = %s\n", error.c_str());
}

float testApp::calcutlateCarbonEmission( int watts )
{
	return ((float) watts / 600 / 443) * 1000;
}


void testApp::parseJSON(string s) 
{

	bool parsingSuccessful = reader.parse( s, root );
	if ( !parsingSuccessful ) {
		std::cout  << "Failed to parse JSON\n" << reader.getFormatedErrorMessages();
		return;
	}

	Json::Value text;
	
	
	//cout << root["fp_data"] <<endl;
	//cout << root["home"] <<endl;	
	//cout << root["hive_data"] <<endl;
	//cout << "+++++++++++" <<endl;
	
	
	if( root["fp_data"]["avg"].asInt() != 0 )
	{
		
		text = root["fp_data"];
		
	//	temperature = ofToFloat(text["temp"].asString());
	//	minimum = (float) text["min"].asInt();
	//	maximum = (float) text["max"].asInt();
		average = (float) text["avg"].asInt();
		
		if( temperatureGroupUpdateIndex1==temperatureCollectionSize )
			temperatureGroupUpdateIndex1 = 0;
		
		temperatureCollectionGroup1[ temperatureGroupUpdateIndex1 ] = average;
		temperatureGroupUpdateIndex1++;
		
		
		cout << "world - average: " << average << "   " << temperatureGroupUpdateIndex1 << endl;
	//	cout << "minimum: " << minimum << endl;
	//	cout << "maximum: " << maximum << endl;
	//	cout << "average: " << average << endl;	
	}
	
	else if( root["home"]["whole"].asInt() != 0 )
	{
		if( temperatureGroupUpdateIndex2==temperatureCollectionSize )
			temperatureGroupUpdateIndex2 = 0;
		
		text = root["home"];
		
		average = (float) text["whole"].asInt();
		cout << "us - average: " << average << endl;	
		temperatureCollectionGroup2[ temperatureGroupUpdateIndex2 ] = average;
		
		
		average = (float) text["app3"].asInt();
		cout << "sound - average: " << average << endl;	
		
		temperatureCollectionGroup21[ temperatureGroupUpdateIndex2 ] = average;
		
		
		temperatureGroupUpdateIndex2++;
	}
	
	else if( ofToInt(root["hive_data"]["curr_home"].asString()) != 0 )
	{
		if( temperatureGroupUpdateIndex3==temperatureCollectionSize )
			temperatureGroupUpdateIndex3 = 0;
		
		text = root["hive_data"];
		
		average = ofToInt( text["curr_home"].asString() );
		cout << "visual - average: " << average << endl;	
		
		temperatureCollectionGroup3[ temperatureGroupUpdateIndex3 ] = average;

		//cout << text["curr_home"].asString() << endl;
		
		temperatureGroupUpdateIndex3++;
	}

	else if(root["hid"].asString() != "")
	{
		cout << "************" << endl;
		cout << "LOGGING IN" << endl;
		
		hid = root["hid"].asString();
		key = root["key"].asString();
		cout << "HID: " << hid << " KEY: " << key << endl;
		
	}	
	
		
	
}


//--------------------------------------------------------------
void testApp::update(){
	std::stringstream instantReadingURL;
	std::stringstream macURL;
	
	timer++;
	//cout << timer << endl;
	if(timer > 100)
	{		
		cout << "************" << endl;
		cout << "REFRESH FEED" << endl;
		//http.addUrl("http://status2.energyhive.co.uk/fp_data.json");
		instantReadingURL << "http://status2.energyhive.co.uk/hive_data.json?hid=" << hid << "&key=" << key << "&avg=0";
		cout << instantReadingURL.str() << endl;
		http.addUrl(instantReadingURL.str());
		
		macURL << "http://www.dehems.org/data/get_status.json?iHateIE=1285496040&mac=" << MAC;
		cout << macURL.str() << endl;
		http.addUrl(macURL.str());
		
		timer = 0;	
	}
}

//--------------------------------------------------------------
void testApp::draw(){
	ofSetColor(0, 0, 0);

	
	
	
	
	
	ofEnableAlphaBlending();
	
	ofFill();	
	
	int val;
	
	int scale = 5;
	
	for(int i=0; i<temperatureCollectionSize; i++)
	{
		//cout << temperatureCollectionGroup1[ i ] << endl;
		/*
		if( temperatureCollectionGroup1[ i ] != DEFAULT_TEMP_COLLECTION )
		{
			val = temperatureCollectionGroup1[ i ];
			
			myFont.drawString("world average", 50, 100);
			myFont.drawString( ofToString( val ), 50, 140);
			
			ofSetColor(255,0,0,255/temperatureCollectionSize);
			ofCircle( 100 , 400 , val/10);
			//cout << val << endl;
			
		}*/
		
		if(temperatureCollectionGroup2[ i ] != DEFAULT_TEMP_COLLECTION &&
		   temperatureCollectionGroup21[ i ] != DEFAULT_TEMP_COLLECTION && 
		   temperatureCollectionGroup3[ i ] != DEFAULT_TEMP_COLLECTION
		   )
		{
			
			val = temperatureCollectionGroup1[ i ] = (temperatureCollectionGroup2[ i ] + temperatureCollectionGroup21[ i ] + temperatureCollectionGroup3[ i ]) / 3;
			
			ofSetColor(255,0,0,255);
			myFont.drawString(LABEL_1, 50, 100);
			
			ofSetColor(255,0,0,255/temperatureCollectionSize);
			myFont.drawString( ofToString( val ), 50, 140);
			
			ofCircle( 100 , 400 , val/scale);
			 
			if( i==temperatureCollectionSize-1)
			{
				ofSetColor(0,0,0,255);
				myFont.drawString("CO2 = " + ofToString( calcutlateCarbonEmission( val ) ) + "g CO2" , 50, 550);
			}
		}
		
		
		if( temperatureCollectionGroup2[ i ] != DEFAULT_TEMP_COLLECTION )
		{
			val = temperatureCollectionGroup2[ i ];
			
			ofSetColor(0,255,0,255);			
			myFont.drawString(LABEL_2, 50+ X_ANCHOR, 100);
			
			ofSetColor(0,255,0,255/temperatureCollectionSize);
			myFont.drawString( ofToString( val ), 50+ X_ANCHOR, 140);			
			
			ofCircle( 100 + X_ANCHOR , 400 ,val/scale);
		}
		
		if( temperatureCollectionGroup21[ i ] != DEFAULT_TEMP_COLLECTION )
		{
			val = temperatureCollectionGroup21[ i ];
			
			ofSetColor(0,0,255,255);			
			myFont.drawString(LABEL_3, 50+ X_ANCHOR*2, 100);
			
			ofSetColor(0,0,255,255/temperatureCollectionSize);
			myFont.drawString( ofToString( val ), 50+ X_ANCHOR*2, 140);
			
			ofCircle( 100 + X_ANCHOR*2 , 400 ,val/scale);
		}
		
		if( temperatureCollectionGroup3[ i ] != DEFAULT_TEMP_COLLECTION )
		{
			val = temperatureCollectionGroup3[ i ];
			
			ofSetColor(100,100,100,255);			
			myFont.drawString(LABEL_4, 50+ X_ANCHOR*3, 100);			
			
			ofSetColor(100,100,100,255/temperatureCollectionSize);
			myFont.drawString( ofToString( val ), 50+ X_ANCHOR*3, 140);
			
			ofCircle( 100 + X_ANCHOR*3 , 400 ,val/scale);
		}

	}
	//cout << "____________" <<endl;
	
	ofDisableAlphaBlending();
	
}

//--------------------------------------------------------------
void testApp::keyPressed(int key){

}

//--------------------------------------------------------------
void testApp::keyReleased(int key){

}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}

